﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.OracleClient;
using System.IO;
using System.Diagnostics;

using System.Runtime.InteropServices;

using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;

using shudiangis.Common;
using shudiangis.Enum;
using shudiangis.Global;

namespace shudiangis
{
    public sealed partial class MainForm : Form
    {
        #region class private members
        private IMapControl3 m_mapControl = null;
        private string m_mapDocumentName = string.Empty;
        private IPointCollection pPointColl;

        #endregion

        #region class public members
        public IFeatureWorkspace pSdeWorkspace;

        #endregion
        
        #region class constructor
        public MainForm()
        {
            InitializeComponent();
        }
        #endregion

        #region 窗口变量定义
        public LoginForm loginform;
        public UserManagerForm usermanagerform;
        public DepManagerForm depmanagerform;
        public QuanXianManagerForm quanxianmanagerform;
        public UserLoginInfoForm userlogininfoform;
        public TuCengManagerForm tucengmanagerform;
        public StyleManagerForm stylemanagerform;
        public TuCengDispOrderManagerForm tucengdispordermanagerform;
        public MicroClimateForm microclimateform;
        public WireTemperatureForm wiretemperatureform;
        public SaltDensityForm saltdensityform;
        public InfraredTemperatureForm infraredtemperatureform;
        public InfraredImagingForm infraredimagingform;
        public HarmonicForm harmonicform;
        public ScadaInfoForm scadainfoform;
        public CrossingForm crossingform;
        public LightningIncidenceForm lightningincidenceform;
        public SubstationLightningAnalyseForm substationlightninganalyseform;
        public WireLightningAnalyseForm wirelightninganalyseform;
        public AreaLightningAnalyseForm arealightninganalyseform;
        public ObjectInfoForm objectinfoform;
        public SubstationSpecialAreaForm substationspecialareaform;
        public WireSpecialAreaForm wirespecialareaform;
        public TowerSpecialAreaForm towerspecialareaform;
        public SubstationBeforehandSetForm substationbeforehandsetform;
        public WireBeforehandSetForm wirebeforehandsetform;
        public WireBeforehandForm wirebeforehandform;
        public SubstationBeforehandForm substationbeforehandform;
        public BeforehandAnalyseForm beforehandanalyseform;
        public AccidentDirectForm accidentdirectform;
        public AccidentRecordEditForm accidentrecordeditform;
        public ExperienceEditForm experienceeditform;
        public AccidentMapForm accidentmapform;
        public EagleForm eagleform;

        #endregion

        private void MainForm_Load(object sender, EventArgs e)
        {
            //License
            IAoInitialize pAoInit = new AoInitializeClass();
            pAoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcView);

            //get the MapControl
            m_mapControl = (IMapControl3)axMapControlMain.Object;

            //disable the Save menu (since there is no document yet)
            menuSaveDoc.Enabled = false;

            //连接SDE数据库            
            //GetSdeData();
            
            pSdeWorkspace = UserDatabaseOperation.openSDEWorkspace("zymobile", "esri_sde", "port:5151", "sde", "sde", "", "sde.DEFAULT");
            //pSdeWorkspace = UserDatabaseOperation.openSDEWorkspace("192.168.0.15", "esri_sde", "port:5151", "sde", "sde", "", "sde.DEFAULT");

            //加载图层
            AddSdeLayer();
            //this.axMapControlMain.LoadMxFile(@"E:\work\大同GIS项目\山西地图.mxd");


        }        

        #region Main Menu event handlers
        private void menuNewDoc_Click(object sender, EventArgs e)
        {
            //execute New Document command
            ICommand command = new CreateNewDocument();
            command.OnCreate(m_mapControl.Object);
            command.OnClick();
        }

        private void menuOpenDoc_Click(object sender, EventArgs e)
        {
            //execute Open Document command
            ICommand command = new ControlsOpenDocCommandClass();
            command.OnCreate(m_mapControl.Object);
            command.OnClick();
        }

        private void menuSaveDoc_Click(object sender, EventArgs e)
        {
            //execute Save Document command
            if (m_mapControl.CheckMxFile(m_mapDocumentName))
            {
                //create a new instance of a MapDocument
                IMapDocument mapDoc = new MapDocumentClass();
                mapDoc.Open(m_mapDocumentName, string.Empty);

                //Make sure that the MapDocument is not readonly
                if (mapDoc.get_IsReadOnly(m_mapDocumentName))
                {
                    MessageBox.Show("Map document is read only!");
                    mapDoc.Close();
                    return;
                }

                //Replace its contents with the current map
                mapDoc.ReplaceContents((IMxdContents)m_mapControl.Map);

                //save the MapDocument in order to persist it
                mapDoc.Save(mapDoc.UsesRelativePaths, false);

                //close the MapDocument
                mapDoc.Close();
            }
        }

        private void menuSaveAs_Click(object sender, EventArgs e)
        {
            //execute SaveAs Document command
            ICommand command = new ControlsSaveAsDocCommandClass();
            command.OnCreate(m_mapControl.Object);
            command.OnClick();
        }

        private void menuExitApp_Click(object sender, EventArgs e)
        {
            //exit the application
            Application.Exit();
        }
        #endregion

        //listen to MapReplaced evant in order to update the statusbar and the Save menu
        private void axMapControl1_OnMapReplaced(object sender, IMapControlEvents2_OnMapReplacedEvent e)
        {
            //get the current document name from the MapControl
            m_mapDocumentName = m_mapControl.DocumentFilename;

            //if there is no MapDocument, diable the Save menu and clear the statusbar
            if (m_mapDocumentName == string.Empty)
            {
                menuSaveDoc.Enabled = false;
                statusBarXY.Text = string.Empty;
            }
            else
            {
                //enable the Save manu and write the doc name to the statusbar
                menuSaveDoc.Enabled = true;
                statusBarXY.Text = System.IO.Path.GetFileName(m_mapDocumentName);
            }
        }
        
        private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            statusBarXY.Text = string.Format("{0}, {1}  {2}", e.mapX.ToString("#######.##"), e.mapY.ToString("#######.##"), axMapControlMain.MapUnits.ToString().Substring(4));
        }

        private void menuReLogin_Click(object sender, EventArgs e)
        {
            loginform = new LoginForm();
            loginform.ShowDialog();
        }

        private void menuChangePasswd_Click(object sender, EventArgs e)
        {
            ChangePasswdForm changepasswdform = new ChangePasswdForm();
            changepasswdform.ShowDialog();
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //exit the application
            Application.Exit();
        }

        private void menuUserSet_Click(object sender, EventArgs e)
        {
            usermanagerform = new UserManagerForm();
            usermanagerform.ShowDialog();
        }

        private void menuDepSet_Click(object sender, EventArgs e)
        {
            depmanagerform = new DepManagerForm();
            depmanagerform.ShowDialog();
        }

        private void menuQuanXianSet_Click(object sender, EventArgs e)
        {
            quanxianmanagerform = new QuanXianManagerForm();
            quanxianmanagerform.ShowDialog();
        }

        private void menuUserLoginInfo_Click(object sender, EventArgs e)
        {
            userlogininfoform = new UserLoginInfoForm();
            userlogininfoform.ShowDialog();
        }

        private void menuZoomIn_Click(object sender, EventArgs e)
        {
            //实现地图放大功能
            //Create a command instance.
            ICommand command = new ESRI.ArcGIS.Controls.ControlsMapZoomInToolClass();

            //Pass the MapControl to the OnCreate method.
            command.OnCreate(axMapControlMain.Object);

            //Set the MapControl's current tool.
            axMapControlMain.CurrentTool = command as ITool;

            //Call OnClick.
            command.OnClick();

        }

        private void menuZoomOut_Click(object sender, EventArgs e)
        {
            //实现地图缩小功能
            //Create a command instance.
            ICommand command = new ESRI.ArcGIS.Controls.ControlsMapZoomOutToolClass();

            //Pass the MapControl to the OnCreate method.
            command.OnCreate(axMapControlMain.Object);

            //Set the MapControl's current tool.
            axMapControlMain.CurrentTool = command as ITool;

            //Call OnClick.
            command.OnClick();
        }

        private void menuPan_Click(object sender, EventArgs e)
        {
            //实现地图漫游功能
            //Create a command instance.
            ICommand command = new ESRI.ArcGIS.Controls.ControlsMapPanToolClass();

            //Pass the MapControl to the OnCreate method.
            command.OnCreate(axMapControlMain.Object);

            //Set the MapControl's current tool.
            axMapControlMain.CurrentTool = command as ITool;

            //Call OnClick.
            command.OnClick();
        }

        private void menuFullScreen_Click(object sender, EventArgs e)
        {
            //实现地图全屏显示功能
            //Create a command instance.
            ICommand command = new ESRI.ArcGIS.Controls.ControlsMapFullExtentCommandClass();

            //Pass the MapControl to the OnCreate method.
            command.OnCreate(axMapControlMain.Object);

            //Set the MapControl's current tool.
            axMapControlMain.CurrentTool = command as ITool;

            //Call OnClick.
            command.OnClick();
        }

        private void menuSelectDefault_Click(object sender, EventArgs e)
        {
            //缺省可以在地图窗口选择几何图形对象，文本对象
        }

        private void menuSelectGeometry_Click(object sender, EventArgs e)
        {
            //使只能选择几何对象

        }

        private void menuSelectText_Click(object sender, EventArgs e)
        {
            //使只能选择文本对象

        }

        private void menuRefresh_Click(object sender, EventArgs e)
        {
            //刷新地图窗口
            //Create a command instance.
            ICommand command = new ESRI.ArcGIS.Controls.ControlsMapRefreshViewCommandClass();

            //Pass the MapControl to the OnCreate method.
            command.OnCreate(axMapControlMain.Object);

            //Set the MapControl's current tool.
            axMapControlMain.CurrentTool = command as ITool;

            //Call OnClick.
            command.OnClick();

        }

        private void menuDefaultView_Click(object sender, EventArgs e)
        {            
            //地图窗口显示主视图
            //Create a command instance.
            ICommand command = new ESRI.ArcGIS.Controls.ControlsMapFullExtentCommandClass();

            //Pass the MapControl to the OnCreate method.
            command.OnCreate(axMapControlMain.Object);

            //Set the MapControl's current tool.
            axMapControlMain.CurrentTool = command as ITool;

            //Call OnClick.
            command.OnClick();
        }

        private void menuPreviousView_Click(object sender, EventArgs e)
        {
            //前一视图
            
        }

        private void menuNextView_Click(object sender, EventArgs e)
        {
            //后一视图
            
        }

        private void menuBookMark_Click(object sender, EventArgs e)
        {
            //书签管理
           
        }

        private void menuCutLine_Click(object sender, EventArgs e)
        {
            //线路打断

        }

        private void menuMergeLine_Click(object sender, EventArgs e)
        {
            //线路合并

        }

        private void menuCutArea_Click(object sender, EventArgs e)
        {
            //分割面对象

        }

        private void menuMergeArea_Click(object sender, EventArgs e)
        {
            //面对象合并

        }

        private void menuObjectMove_Click(object sender, EventArgs e)
        {
            //移动对象

        }

        private void menuObjectDelete_Click(object sender, EventArgs e)
        {
            //删除对象

        }

        private void menuTuCengManager_Click(object sender, EventArgs e)
        {
            //图层管理
            tucengmanagerform = new TuCengManagerForm();
            tucengmanagerform.ShowDialog();
        }

        private void menuStyleManager_Click(object sender, EventArgs e)
        {
            //几何对象显示样式管理
            stylemanagerform = new StyleManagerForm();
            stylemanagerform.ShowDialog();
        }

        private void menuTuCengDispOrder_Click(object sender, EventArgs e)
        {
            //图层加载显示顺序管理
            tucengdispordermanagerform = new TuCengDispOrderManagerForm();
            tucengdispordermanagerform.ShowDialog();
        }

        private void menuMeasureDistance_Click(object sender, EventArgs e)
        {
            //测量长度
            //Create a command instance.
            ICommand command = new ESRI.ArcGIS.Controls.ControlsMapMeasureToolClass();

            //Pass the MapControl to the OnCreate method.
            command.OnCreate(axMapControlMain.Object);

            //Set the MapControl's current tool.
            axMapControlMain.CurrentTool = command as ITool;

            //Call OnClick.
            command.OnClick();
        }

        private void menuMeasureArea_Click(object sender, EventArgs e)
        {
            //测量面积
            //Create a command instance.
            ICommand command = new ESRI.ArcGIS.Controls.ControlsMapMeasureToolClass();

            //Pass the MapControl to the OnCreate method.
            command.OnCreate(axMapControlMain.Object);

            //Set the MapControl's current tool.
            axMapControlMain.CurrentTool = command as ITool;
            //command.Category

            //Call OnClick.
            command.OnClick();
        }

        private void menuMicroclimate_Click(object sender, EventArgs e)
        {
            //显示线路上所有监测点的微气象信息
            microclimateform = new MicroClimateForm();
            microclimateform.ShowDialog();

        }

        private void menuWireTemperature_Click(object sender, EventArgs e)
        {
            //显示线路上所有监测点的导线温度
            wiretemperatureform = new WireTemperatureForm();
            wiretemperatureform.ShowDialog();
        }

        private void menuSaltDensity_Click(object sender, EventArgs e)
        {
            //显示线路上所有监测点的盐密信息
            saltdensityform = new SaltDensityForm();
            saltdensityform.ShowDialog();

        }

        private void menuWireTidalCurrent_Click(object sender, EventArgs e)
        {
            //如果当前在地图窗口选择了线路，则显示当前选择线路的电流走向,并在地图窗口显示整条线路的范围
            //如果没有选择线路，则显示所有线路的电流走向

        }

        private void menuInfraredTemperature_Click(object sender, EventArgs e)
        {
            //显示当前选择变电站的红外测温信息
            infraredtemperatureform = new InfraredTemperatureForm();
            infraredtemperatureform.ShowDialog();
        }

        private void menuInfraredImaging_Click(object sender, EventArgs e)
        {
            //显示当前选择变电站的红外成像信息
            infraredimagingform = new InfraredImagingForm();
            infraredimagingform.ShowDialog();
        }

        private void menuHarmonic_Click(object sender, EventArgs e)
        {
            //显示当前选择变电站内的谐波信息
            harmonicform = new HarmonicForm();
            harmonicform.ShowDialog();
        }

        private void menuScadaInfo_Click(object sender, EventArgs e)
        {
            //显示当前选择变电站内的SCADA信息
            scadainfoform = new ScadaInfoForm();
            scadainfoform.ShowDialog();
        }

        private void menuCrossing_Click(object sender, EventArgs e)
        {
            //线路交叉跨越的对象和类型列表
            crossingform = new CrossingForm();
            crossingform.ShowDialog();

        }

        private void menuLightningIncidence_Click(object sender, EventArgs e)
        {
            //选择雷区，分析去雷区范围内的电力设施
            //弹出界面显示影响的电力设施详细情况
            lightningincidenceform = new LightningIncidenceForm();
            lightningincidenceform.ShowDialog();

        }

        private void menuSubstationLightningAnalyse_Click(object sender, EventArgs e)
        {
            //变电站落雷情况分析
            //选择变电站，设定分析范围，设定落雷的起止时间，分析在该范围内的落雷情况，并实时的绘制在地图窗口中
            //绘制落雷区域的速度可调
            substationlightninganalyseform = new SubstationLightningAnalyseForm();
            substationlightninganalyseform.ShowDialog();

        }

        private void menuWireLightningAnalyse_Click(object sender, EventArgs e)
        {
            //线路两侧落雷情况分析
            //选择输电线路，设定分析范围，设定落雷的起止时间，分析在该范围内的落雷情况，并实时的绘制在地图窗口中
            //绘制落雷区域的速度可调
            wirelightninganalyseform = new WireLightningAnalyseForm();
            wirelightninganalyseform.ShowDialog();
        }

        private void menuAreaLightningAnalyse_Click(object sender, EventArgs e)
        {
            //指定区域落雷情况分析
            //选择线路名称，设定起止杆塔号，设置线路两侧的范围，设置落雷的起止时间，分析在该范围内的落雷情况，并实时的绘制在地图窗口中
            //绘制落雷区域的速度可调
            arealightninganalyseform = new AreaLightningAnalyseForm();
            arealightninganalyseform.ShowDialog();
        }

        private void menuObjectInfo_Click(object sender, EventArgs e)
        {
            //在地图窗口中选中设备几何，显示当前选择对象的设备台帐信息
            objectinfoform = new ObjectInfoForm();
            objectinfoform.ShowDialog();

        }

        private void menuSubstationSpecialArea_Click(object sender, EventArgs e)
        {
            //变电站特殊区域分析
            //在地图窗口中选择变电站，分析出变电站落在哪些特殊区域
            substationspecialareaform = new SubstationSpecialAreaForm();
            substationspecialareaform.ShowDialog();

        }

        private void menuWireSpecialArea_Click(object sender, EventArgs e)
        {
            //线路特殊区域分析
            //在地图窗口中选择线路，分析出线路落在哪些特殊区域
            wirespecialareaform = new WireSpecialAreaForm();
            wirespecialareaform.ShowDialog();

        }

        private void menuTowerSpecialArea_Click(object sender, EventArgs e)
        {
            //杆塔特殊区域分析
            //在地图窗口中选择杆塔，分析出杆塔落在哪些特殊区域
            towerspecialareaform = new TowerSpecialAreaForm();
            towerspecialareaform.ShowDialog();
        }

        private void menuSubstationBeforehandSet_Click(object sender, EventArgs e)
        {
            //变电站预警设置
            substationbeforehandsetform = new SubstationBeforehandSetForm();
            substationbeforehandsetform.ShowDialog();

        }

        private void menuWireBeforehandSet_Click(object sender, EventArgs e)
        {
            //输电线路预警设置
            wirebeforehandsetform = new WireBeforehandSetForm();
            wirebeforehandsetform.ShowDialog();
        }

        private void menuWireBeforehand_Click(object sender, EventArgs e)
        {
            //线路预警数据监测
            wirebeforehandform = new WireBeforehandForm();
            wirebeforehandform.ShowDialog();
        }

        private void menuSubstationBeforehand_Click(object sender, EventArgs e)
        {
            //变电站预警数据监测
            substationbeforehandform = new SubstationBeforehandForm();
            substationbeforehandform.ShowDialog();
        }

        private void menuBeforehandAnalyse_Click(object sender, EventArgs e)
        {
            //预警分析结果显示
            beforehandanalyseform = new BeforehandAnalyseForm();
            beforehandanalyseform.ShowDialog();
        }

        private void menuAccidentDirect_Click(object sender, EventArgs e)
        {
            //事故处理
            //首先显示待处理的故障信息
            accidentdirectform = new AccidentDirectForm();
            accidentdirectform.Show();
        }

        private void menuAccidentRecordEdit_Click(object sender, EventArgs e)
        {
            //录入故障信息
            accidentrecordeditform = new AccidentRecordEditForm();
            accidentrecordeditform.ShowDialog();

        }

        private void menuExperienceEdit_Click(object sender, EventArgs e)
        {
            //录入故障处理经验信息
            experienceeditform = new ExperienceEditForm();
            experienceeditform.ShowDialog();

        }

        private void menuAccidentMap_Click(object sender, EventArgs e)
        {
            //绘制故障点分布图
            accidentmapform = new AccidentMapForm();
            accidentmapform.ShowDialog();
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            
        }

        /// <summary>
        /// 主视图鼠标按下事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            //1代表左键，2代表右键
            if (e.button == 1)
            {
                switch (GlobalVariableDefined.pMouseOperateState)
                {
                    case (int)enumMouseOperateState.Select:

                        break;
                    case (int)enumMouseOperateState.editing:
                        if (GlobalVariableDefined.CurrentEditLayer == null)
                            return;

                        IFeatureClass pFeatureClass;
                        pFeatureClass = pSdeWorkspace.OpenFeatureClass(GlobalVariableDefined.CurrentEditLayer);
                        if(GlobalVariableDefined.CurrentEditLayer.ToLower()=="SDE.Tower".ToLower())
                        {
                            CreatePointFeatureTower(pFeatureClass, e.mapX, e.mapY);
                            axMapControlMain.Refresh();
                        }
                        else if (GlobalVariableDefined.CurrentEditLayer.ToLower() == "SDE.hv_trolly_wire_500kV".ToLower())
                        {
                            IPoint pPoint=new PointClass();
                            pPoint.PutCoords(e.mapX,e.mapY);
                            object Missing = Type.Missing;

                            pPointColl.AddPoint(pPoint, ref Missing, ref Missing);
                        }
                        else if (GlobalVariableDefined.CurrentEditLayer.ToLower() == "SDE.DirtinessArea_1".ToLower())
                        {
                            IPoint pPoint = new PointClass();
                            pPoint.PutCoords(e.mapX, e.mapY);
                            object Missing = Type.Missing;
                            pPointColl.AddPoint(pPoint, ref Missing, ref Missing);
                        }
                            
                        break;

                    case (int)enumMouseOperateState.Zoom:

                        break;

                    default:

                        break;
                }
            }
            else if (e.button == 2)
            {
                //if (e.button != 2) return;
                //取消鼠标的编辑状态，设为选择状态
                GlobalVariableDefined.pMouseOperateState = (int)enumMouseOperateState.Select;

                System.Drawing.Point p = new System.Drawing.Point();
                p.X = e.x;
                p.Y = e.y;
                contextMenuStrip1.Show(axMapControlMain, p);                

            }

            

        }

        private void axMapControlMain_OnDoubleClick(object sender, IMapControlEvents2_OnDoubleClickEvent e)
        {
            switch (GlobalVariableDefined.pMouseOperateState)
            {
                case (int)enumMouseOperateState.Select:

                    break;
                case (int)enumMouseOperateState.editing:
                    if (GlobalVariableDefined.CurrentEditLayer == null)
                        return;

                    IFeatureClass pFeatureClass;
                    pFeatureClass = pSdeWorkspace.OpenFeatureClass(GlobalVariableDefined.CurrentEditLayer);
                    
                    if (GlobalVariableDefined.CurrentEditLayer.ToLower() == "SDE.hv_trolly_wire_500kV".ToLower())
                    {
                        CreatePolylineFeatureHv_trolly_wire_550kV(pFeatureClass, pPointColl);
                        
                        axMapControlMain.Refresh();

                        //重新初始化全局变量pPointColl，以便下次连续录入线路
                        IPolyline pPolyline = new PolylineClass();
                        pPointColl = pPolyline as IPointCollection;
                    }
                    else if (GlobalVariableDefined.CurrentEditLayer.ToLower() == "SDE.DirtinessArea_1".ToLower())
                    {
                        CreatePolygonFeatureDirtinessArea_1(pFeatureClass, pPointColl);

                        axMapControlMain.Refresh();

                        //初始化全局变量pPointColl
                        IPolygon pPolylgon = new PolygonClass();
                        pPointColl = pPolylgon as IPointCollection;
                    }

                    break;

                case (int)enumMouseOperateState.Zoom:

                    break;

                default:

                    break;
            }

        }

        private void menuEagle_Click(object sender, EventArgs e)
        {
            //显示/隐藏导航图窗口
            if (eagleform == null)
            {
                //eagleform = new EagleForm();
                eagleform = new EagleForm(axMapControlMain);
            }

            ToolStripMenuItem item = sender as ToolStripMenuItem;
            if (item.Checked == true)
            {
                eagleform.Show();
                eagleform.StartPosition = FormStartPosition.Manual;                
                //eagleform.Location = new Point(1024, 0);
                eagleform.Top = this.Top + 80;
                eagleform.Left = this.Right - 245;                
               
            }
            else
            {
                eagleform.Hide();
            }

        }

        private void MainForm_LocationChanged(object sender, EventArgs e)
        {
            if (eagleform != null)
            {
                eagleform.Top = this.Top + 80;
                eagleform.Left = this.Right - 245;
            }
        }

        ///<summary>
        ///加载SDE图层
        ///
        ///</summary>
        private void AddSdeLayer()
        {
            //图层名称
            string[] eleclayerstr = { "SDE.TOWER", 
                                        "SDE.substation_500kV", "SDE.substation_220kV", "SDE.substation_110kV", 
                                        "SDE.hv_trolly_wire_500kV", "SDE.hv_trolly_wire_220kV","SDE.hv_trolly_wire_110kV","SDE.hv_trolly_wire_35kV",
                                        "SDE.DirtinessArea_1","SDE.DirtinessArea_2","SDE.DirtinessArea_3","SDE.DirtinessArea_4" };
            /*
            string[] landbaselayerstr = { "SDE.KFW_POLYGON_SL", "SDE.POLYLINEFCLT", "SDE.LBLPOINT", "SDE.LINEFCLT", 
                                       "SDE.POLYGONFCLT", "SDE.POLYGONANNO", "SDE.POLEFCLT", "SDE.POLEANNO" };
             */
            string[] landbaselayerstr = { "SDE.bount", "SDE.respt", "SDE.road" };

            //图层
            IFeatureLayer layer;
            IFeatureClass pFeatureClass;
            
            /*
            foreach (string s in landbaselayerstr)
            {
                pFeatureClass = pSdeWorkspace.OpenFeatureClass(s);
                layer = new FeatureLayerClass();
                layer.FeatureClass = pFeatureClass;
                layer.Name = pFeatureClass.AliasName;
                m_mapControl.Map.AddLayer(layer);
            }
            */

            IDatasetName pSdeDSName;
            IEnumDatasetName pEnumDSName;
            IWorkspace pWorkspace;
            pWorkspace = pSdeWorkspace as IWorkspace;
            pEnumDSName = pWorkspace.get_DatasetNames(esriDatasetType.esriDTFeatureDataset);
            pSdeDSName = pEnumDSName.Next();

            IFeatureDataset pFeatureDataset;

            while (pSdeDSName != null)
            {
                if (pSdeDSName.Name == "SDE.elec")
                {                    
                    foreach (string ss in eleclayerstr)
                    {
                        pFeatureDataset = pSdeWorkspace.OpenFeatureDataset("elec");
                        pFeatureClass = pSdeWorkspace.OpenFeatureClass(ss);
                        layer = new FeatureLayerClass();
                        layer.FeatureClass = pFeatureClass;
                        layer.Name = pFeatureClass.AliasName;
                        m_mapControl.Map.AddLayer(layer);
                    }
                }
                else if (pSdeDSName.Name == "SDE.landbase")
                {
                    foreach (string ss in landbaselayerstr)
                    {
                        pFeatureDataset = pSdeWorkspace.OpenFeatureDataset("landbase");
                        pFeatureClass = pSdeWorkspace.OpenFeatureClass(ss);
                        layer = new FeatureLayerClass();
                        layer.FeatureClass = pFeatureClass;
                        layer.Name = pFeatureClass.AliasName;
                        m_mapControl.Map.AddLayer(layer);
                    }
                }

                pSdeDSName = pEnumDSName.Next();
            }


            
        }

        /// <summary>
        /// 连接sde数据库，并设定map的图层
        /// </summary>
        private void GetSdeData()
        {
            /**连接sde数据库**/
            //License
            IAoInitialize pAoInit = new AoInitializeClass();
            pAoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcView);

            //Workspace
            IWorkspaceFactory pWorkspaceFactory;
            pWorkspaceFactory = new SdeWorkspaceFactoryClass();

            //PropertySet
            IPropertySet pPropertySet;
            pPropertySet = new PropertySetClass();
            pPropertySet.SetProperty("Service", "esri_sde");
            pPropertySet.SetProperty("Server", "192.168.0.106");
            //pPropertySet.SetProperties("Database","wjgis");
            pPropertySet.SetProperty("Instance", "port:5151");
            pPropertySet.SetProperty("user", "sde");
            pPropertySet.SetProperty("password", "sde");
            pPropertySet.SetProperty("version", "sde.DEFAULT");

            //IFeatureWorkspace对象
            IFeatureWorkspace pSdeWorkspace;

            //IFeatureDataset pFeatureDataset;
            IFeatureClass pFeatureClass;

            //图层
            IFeatureLayer layer;

            try
            {
                //连接
                pSdeWorkspace = (IFeatureWorkspace)pWorkspaceFactory.Open(pPropertySet, 0);

                string[] layerstr = { "SDE.POLYLINEFCLT", "SDE.LBLPOINT", "SDE.LINEFCLT", "SDE.POLYGONFCLT", "SDE.POLYGONANNO", "SDE.POLEFCLT", "SDE.POLEANNO" };
                /*
                //取数据
                //pFeatureDataset = pSdeWorkspace.OpenFeatureDataset("buj");
                pFeatureClass = pSdeWorkspace.OpenFeatureClass("SDE.POLYLINEFCLT");

                //定义图层
                layer = new FeatureLayerClass();
                layer.name = pFeatureClass.AliasName;

                //设定layer的FeatureClass属性
                layer.FeatureClass = pFeatureClass;

                //设定Map的图层
                m_mapControl.Map.AddLayer(layer);
                */
                foreach(string s in layerstr)
                {
                    pFeatureClass = pSdeWorkspace.OpenFeatureClass(s);
                    layer = new FeatureLayerClass();
                    layer.FeatureClass = pFeatureClass;
                    layer.Name = pFeatureClass.AliasName;
                    m_mapControl.Map.AddLayer(layer);
                }
                
            }
            catch (Exception ex)
            {

                MessageBox.Show("SDE数据库不能连接！" + ex.Message);
                
            }
        }

        private void menuSdeEditDelete_Click(object sender, EventArgs e)
        {
            ESRI.ArcGIS.esriSystem.IPropertySet propertySet = new ESRI.ArcGIS.esriSystem.PropertySetClass();

            propertySet.SetProperty("Service", "esri_sde");
            propertySet.SetProperty("Server", "192.168.0.106");
            propertySet.SetProperty("Instance", "port:5151");
            propertySet.SetProperty("user", "sde");
            propertySet.SetProperty("password", "sde");
            propertySet.SetProperty("version", "sde.DEFAULT");

            IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactoryClass();
            IWorkspace workspace = workspaceFactory.Open(propertySet, 0);

            //Cast to IFeatureWorkspace. 
            IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;

            IFeatureClass featureClass = featureWorkspace.OpenFeatureClass("SDE.POLYLINEFCLT");

            IFeature feature;

            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)featureWorkspace;
            IMultiuserWorkspaceEdit muWorkspaceEdit = (IMultiuserWorkspaceEdit)featureWorkspace;

            if (muWorkspaceEdit.SupportsMultiuserEditSessionMode(esriMultiuserEditSessionMode.esriMESMNonVersioned))
            {
                muWorkspaceEdit.StartMultiuserEditing(esriMultiuserEditSessionMode.esriMESMNonVersioned);
                workspaceEdit.StartEditOperation();
                feature = featureClass.GetFeature(1);
                feature.Delete();
                bool hasEdits = false;
                workspaceEdit.HasEdits(ref hasEdits);
                workspaceEdit.StopEditOperation();

                System.Windows.Forms.DialogResult result = System.Windows.Forms.MessageBox.Show("Save Edits?", "Save Edits Dialog", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question);

                if(result == System.Windows.Forms.DialogResult.Yes && hasEdits)
                {
                    workspaceEdit.StopEditing(true);
                }
                else
                {
                    workspaceEdit.StopEditing(false);
                }
            }

        }        

        /// <summary>
        /// 建立点要素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuCreatePointFeature_Click(object sender, EventArgs e)
        {
            IFeatureClass pFeatureClass;            
            pFeatureClass = pSdeWorkspace.OpenFeatureClass("SDE.TOWER"); 
            
            //CreateFeature(pFeatureClass, point);
            CreatePointFeature(pFeatureClass);

        }
                
        public void CreatePointFeature(IFeatureClass featureClass)
        {
            // Ensure the feature class contains points.
            if (featureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint)
            {
                return;
            }

            //先定义一个编辑的工作空间,然后把转化为数据集,最后转化为编辑工作空间, 
            IWorkspaceEdit w = (featureClass as IDataset).Workspace as IWorkspaceEdit;

            //开始事务操作
            w.StartEditing(false);

            //开始编辑 
            w.StartEditOperation(); 

            IGeoDataset geoDataset = featureClass as IGeoDataset;
            ISpatialReference spatialReference = geoDataset.SpatialReference;
            IPoint point = new PointClass();

            //The IPoint interface inherits from the IGeometry interface.
            point.SpatialReference = spatialReference;

            //Assign to the point the mathematical (i.e., full double precision resolution) center of 
            //the x,y domain of this spatial reference.
            double xMin;
            double yMin;
            double xMax;
            double yMax;
            spatialReference.GetDomain(out xMin, out xMax, out yMin, out yMax);

            //point.X = (xMin + xMax) * 0.5;
            //point.Y = (yMin + yMax) * 0.5;

            point.X = 20625220;
            point.Y = 4158522;

            //Snap the double precision center of the domain to a location representable in the domain. 
            //Specifically, a multiple of the resolution and offset from the xMin, yMin of the domain.
            //System.Windows.Forms.MessageBox.Show("Before snapping: " + point.X + ", " + point.Y);
            point.SnapToSpatialReference();
            //System.Windows.Forms.MessageBox.Show("After snapping: " + point.X + ", " + point.Y);


            // Build the feature.
            IFeature feature = featureClass.CreateFeature();
            feature.Shape = point;
            //MessageBox.Show(feature.Extent.ToString());
         
            // Apply the appropriate subtype to the feature.
            ISubtypes subtypes = (ISubtypes)featureClass;
            IRowSubtypes rowSubtypes = (IRowSubtypes)feature;
            if (subtypes.HasSubtype)
            {
                // In this example, the value of 3 represents the Cross subtype.
                rowSubtypes.SubtypeCode = 3;
            }

            // Initialize any default values the feature has.
            rowSubtypes.InitDefaultValues();

            // Update the value on a string field that indicates who installed the feature.
            int contractorFieldIndex = featureClass.FindField("VOLTAGE");
            feature.set_Value(contractorFieldIndex, "110kV");
           
            // Update the value on a string field that indicates who installed the feature.
            contractorFieldIndex = featureClass.FindField("WIRE_name");
            feature.set_Value(contractorFieldIndex, "所属线路的名称");

            // Update the value on a string field that indicates who installed the feature.
            contractorFieldIndex = featureClass.FindField("tower_id_mis");
            feature.set_Value(contractorFieldIndex, "10001");

            // Update the value on a string field that indicates who installed the feature.
            contractorFieldIndex = featureClass.FindField("known_as");
            feature.set_Value(contractorFieldIndex, "杆塔号1#");

            // Commit the new feature to the geodatabase.
            feature.Store();

            //结束编辑 
            w.StopEditOperation();

            //结束事务操作 
            w.StopEditing(true); 
        }

        public void CreatePointFeatureTower(IFeatureClass featureClass, double x, double y)
        {
            // Ensure the feature class contains points.
            if (featureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint)
            {
                return;
            }

            //先定义一个编辑的工作空间,然后把转化为数据集,最后转化为编辑工作空间, 
            IWorkspaceEdit w = (featureClass as IDataset).Workspace as IWorkspaceEdit;

            //开始事务操作
            w.StartEditing(false);

            //开始编辑 
            w.StartEditOperation();

            IGeoDataset geoDataset = featureClass as IGeoDataset;
            ISpatialReference spatialReference = geoDataset.SpatialReference;
            IPoint point = new PointClass();

            //The IPoint interface inherits from the IGeometry interface.
            point.SpatialReference = spatialReference;

            //Assign to the point the mathematical (i.e., full double precision resolution) center of 
            //the x,y domain of this spatial reference.
            double xMin;
            double yMin;
            double xMax;
            double yMax;
            spatialReference.GetDomain(out xMin, out xMax, out yMin, out yMax);
                        
            point.X = x;
            point.Y = y;

            //Snap the double precision center of the domain to a location representable in the domain. 
            //Specifically, a multiple of the resolution and offset from the xMin, yMin of the domain.
            //System.Windows.Forms.MessageBox.Show("Before snapping: " + point.X + ", " + point.Y);
            point.SnapToSpatialReference();
            //System.Windows.Forms.MessageBox.Show("After snapping: " + point.X + ", " + point.Y);
            
            // Build the feature.
            IFeature feature = featureClass.CreateFeature();
            feature.Shape = point;
            //MessageBox.Show(feature.Extent.ToString());

            // Apply the appropriate subtype to the feature.
            ISubtypes subtypes = (ISubtypes)featureClass;
            IRowSubtypes rowSubtypes = (IRowSubtypes)feature;
            if (subtypes.HasSubtype)
            {
                // In this example, the value of 3 represents the Cross subtype.
                rowSubtypes.SubtypeCode = 3;
            }

            // Initialize any default values the feature has.
            rowSubtypes.InitDefaultValues();

            // Update the value on a string field that indicates who installed the feature.
            int contractorFieldIndex = featureClass.FindField("VOLTAGE");
            feature.set_Value(contractorFieldIndex, "110kV");

            // Update the value on a string field that indicates who installed the feature.
            contractorFieldIndex = featureClass.FindField("WIRE_name");
            feature.set_Value(contractorFieldIndex, "所属线路的名称");

            // Update the value on a string field that indicates who installed the feature.
            contractorFieldIndex = featureClass.FindField("tower_id_mis");
            feature.set_Value(contractorFieldIndex, "10001");

            // Update the value on a string field that indicates who installed the feature.
            contractorFieldIndex = featureClass.FindField("known_as");
            feature.set_Value(contractorFieldIndex, "杆塔号1#");

            // Commit the new feature to the geodatabase.
            feature.Store();

            //结束编辑 
            w.StopEditOperation();

            //结束事务操作 
            w.StopEditing(true);
        }

        /// <summary>
        /// 建立线要素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuCreatePolylineFeature_Click(object sender, EventArgs e)
        {       
            IFeatureClass pFeatureClass;            
            pFeatureClass = pSdeWorkspace.OpenFeatureClass("SDE.HV_TROLLY_WIRE_500kV");
            //CreatePolylineFeature(pFeatureClass);
            createMultiPolylineFeature(pFeatureClass);  
        
        }              
        
        /// <summary>
        /// 建立单条线段
        /// </summary>
        /// <param name="featureClass"></param>
        public void CreatePolylineFeature(IFeatureClass featureClass)    
        {        
            //Function is designed to work with polyline data        
            if (featureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline)             
            { 
                return; 
            }

            IGeoDataset geoDataset = featureClass as IGeoDataset;
            ISpatialReference spatialReference = geoDataset.SpatialReference;

            //先定义一个编辑的工作空间,然后把转化为数据集,最后转化为编辑工作空间, 
            IWorkspaceEdit w = (featureClass as IDataset).Workspace as IWorkspaceEdit;

            //开始事务操作
            w.StartEditing(false);

            //开始编辑 
            w.StartEditOperation(); 

            //create a geometry for the features shape        
            ESRI.ArcGIS.Geometry.IPolyline polyline = new ESRI.ArcGIS.Geometry.PolylineClass();        
            ESRI.ArcGIS.Geometry.IPoint point = new ESRI.ArcGIS.Geometry.PointClass();
            point.X = 20625320;
            point.Y = 4158622;
                        
            polyline.FromPoint = point;
            
            point = new ESRI.ArcGIS.Geometry.PointClass();
            point.X = 20625320 + 1000;
            point.Y = 4158622 + 1000;        
            polyline.ToPoint = point;

            polyline.SpatialReference = spatialReference;
            polyline.SnapToSpatialReference();

            IFeature feature = featureClass.CreateFeature();
            //Apply the constructed shape to the new features shape        
            feature.Shape = polyline;

            ISubtypes subtypes = (ISubtypes)featureClass;        
            IRowSubtypes rowSubtypes = (IRowSubtypes)feature;        
            if (subtypes.HasSubtype)  // does the feature class have subtypes?        
            {            
                rowSubtypes.SubtypeCode = 1; //in this example 1 represents the Primary Pipeline subtype        
            }

            // initalize any default values that the feature has        
            rowSubtypes.InitDefaultValues();
            //Commit the default values in the feature to the database        
            feature.Store();
            //update the value on a string field that indicates who installed the feature.        
            feature.set_Value(feature.Fields.FindField("wire_id_mis"), "10002");
            feature.set_Value(feature.Fields.FindField("known_as"), "线路名称");
            feature.set_Value(feature.Fields.FindField("voltage"), "500kV");

            //Commit the updated values in the feature to the database        
            feature.Store();

            //结束编辑 
            w.StopEditOperation();

            //结束事务操作 
            w.StopEditing(true); 
        }

        public void CreatePolylineFeatureHv_trolly_wire_550kV(IFeatureClass featureClass,IPointCollection pPointColl)
        {
            //Function is designed to work with polyline data        
            if (featureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline)
            {
                return;
            }

            IGeoDataset geoDataset = featureClass as IGeoDataset;
            ISpatialReference spatialReference = geoDataset.SpatialReference;

            //先定义一个编辑的工作空间,然后把转化为数据集,最后转化为编辑工作空间, 
            IWorkspaceEdit w = (featureClass as IDataset).Workspace as IWorkspaceEdit;

            //开始事务操作
            w.StartEditing(false);

            //开始编辑 
            w.StartEditOperation();

            //create a geometry for the features shape        
            ESRI.ArcGIS.Geometry.IPolyline polyline = new ESRI.ArcGIS.Geometry.PolylineClass();
            polyline = pPointColl as IPolyline;

            polyline.SpatialReference = spatialReference;
            polyline.SnapToSpatialReference();

            IFeature feature = featureClass.CreateFeature();
            //Apply the constructed shape to the new features shape        
            feature.Shape = polyline;

            ISubtypes subtypes = (ISubtypes)featureClass;
            IRowSubtypes rowSubtypes = (IRowSubtypes)feature;
            if (subtypes.HasSubtype)  // does the feature class have subtypes?        
            {
                rowSubtypes.SubtypeCode = 1; //in this example 1 represents the Primary Pipeline subtype        
            }

            // initalize any default values that the feature has        
            rowSubtypes.InitDefaultValues();
            //Commit the default values in the feature to the database        
            feature.Store();
            //update the value on a string field that indicates who installed the feature.        
            feature.set_Value(feature.Fields.FindField("wire_id_mis"), "10002");
            feature.set_Value(feature.Fields.FindField("known_as"), "线路名称");
            feature.set_Value(feature.Fields.FindField("voltage"), "500kV");

            //Commit the updated values in the feature to the database        
            feature.Store();

            //结束编辑 
            w.StopEditOperation();

            //结束事务操作 
            w.StopEditing(true);
        }

        /// <summary>
        /// 建立多个点的线，用IFeatureBuffer接口
        /// </summary>
        /// <param name="featureClass"></param>
        private void createMultiPolylineFeature(IFeatureClass featureClass)
        {

             //Function is designed to work with polyline data        
            if (featureClass.ShapeType != ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline)             
            { 
                return; 
            }

            IGeoDataset geoDataset = featureClass as IGeoDataset;
            ISpatialReference spatialReference = geoDataset.SpatialReference;

            IFeatureBuffer pFeatureBuffer;
            IFeatureCursor pFeatureCursor;
            IFeature pFeature;
            IPolyline pPolyline;
            IPoint pt;
          
            //先定义一个编辑的工作空间,然后把转化为数据集,最后转化为编辑工作空间, 
            IWorkspaceEdit w = (featureClass as IDataset).Workspace as IWorkspaceEdit;

            //开始事务操作
            w.StartEditing(false);

            //开始编辑 
            w.StartEditOperation(); 

    
            pFeatureBuffer = featureClass.CreateFeatureBuffer();
            pFeatureCursor = featureClass.Insert(true);
            pFeature = pFeatureBuffer as IFeature;
            pPolyline = new PolylineClass();
            
            //Create 100 features using FeatureBuffer and insert into a feature cursor
            for(int i =0; i<=99;i++)
            {        
                //Create the polyline geometry to assign to the new feature
                pt = new PointClass();
                pt.X = 20625320 + i*100;
                pt.Y = 4158622 + i*100;
                pPolyline.FromPoint = pt;
                
                pt = new PointClass();
                pt.X = 20625320 + i * 100 + 100;
                pt.Y = 4158622 + i*100 + 100;
                pPolyline.ToPoint = pt;

                pPolyline.SpatialReference = spatialReference;
                
                //Set the feature's shape
                pFeature.Shape = pPolyline;
                
                //Insert the feature into the feature cursor
                pFeatureCursor.InsertFeature(pFeatureBuffer);
            }
            
            //Flush the feature cursor to the database
            pFeatureCursor.Flush();

            //结束编辑 
            w.StopEditOperation();

            //结束事务操作 
            w.StopEditing(true); 

        }

        /// <summary>
        /// 建立面要素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void createPolygonFeature_Click(object sender, EventArgs e)
        {
            IFeatureClass pFeatureClass;
            pFeatureClass = pSdeWorkspace.OpenFeatureClass("SDE.DirtinessArea_4");

            IGeoDataset geoDataset = pFeatureClass as IGeoDataset;
            ISpatialReference spatialReference = geoDataset.SpatialReference;

            IFeatureBuffer pFeatureBuffer;
            IFeatureCursor pFeatureCursor;
            IFeature pFeature;
            IPolygon pPolygon;

            pFeatureBuffer = pFeatureClass.CreateFeatureBuffer();
            pFeatureCursor = pFeatureClass.Insert(true);
            pFeature = pFeatureBuffer as IFeature;
            pPolygon = new PolygonClass();
            IPointCollection pPointColl;
            pPointColl = pPolygon as IPointCollection;            

            //先定义一个编辑的工作空间,然后把转化为数据集,最后转化为编辑工作空间, 
            IWorkspaceEdit w = (pFeatureClass as IDataset).Workspace as IWorkspaceEdit;

            //开始事务操作
            w.StartEditing(false);

            //开始编辑 
            w.StartEditOperation();

            object Missing = Type.Missing;

            IPoint pt1 = new PointClass();
            pt1.PutCoords(20625320, 4158622);
            pPointColl.AddPoint(pt1, ref Missing, ref Missing);

            IPoint pt2 = new PointClass();
            pt2.PutCoords(20625320, 4158622+200);
            pPointColl.AddPoint(pt2, ref Missing, ref Missing);

            IPoint pt3 = new PointClass();
            pt3.PutCoords(20625320+200, 4158622 + 200);
            pPointColl.AddPoint(pt3, ref Missing, ref Missing);

            IPoint pt4 = new PointClass();
            pt4.PutCoords(20625320+200, 4158622);
            pPointColl.AddPoint(pt4, ref Missing, ref Missing);

            pPolygon = pPointColl as IPolygon;

            //封闭面对象
            pPolygon.Close();

            pPolygon.SpatialReference = spatialReference;
            pFeature.Shape = pPolygon;

            pFeatureCursor.InsertFeature(pFeatureBuffer);

            //Flush the feature cursor to the database
            pFeatureCursor.Flush();

            //结束编辑 
            w.StopEditOperation();

            //结束事务操作 
            w.StopEditing(true);

            axMapControlMain.Refresh();
        }      
        
        public void CreatePolygonFeatureDirtinessArea_1(IFeatureClass pFeatureClass, IPointCollection pPointColl)
        {
            IGeoDataset geoDataset = pFeatureClass as IGeoDataset;
            ISpatialReference spatialReference = geoDataset.SpatialReference;

            IFeatureBuffer pFeatureBuffer;
            IFeatureCursor pFeatureCursor;
            IFeature pFeature;
            IPolygon pPolygon;

            pFeatureBuffer = pFeatureClass.CreateFeatureBuffer();
            pFeatureCursor = pFeatureClass.Insert(true);
            pFeature = pFeatureBuffer as IFeature;
            pPolygon = new PolygonClass();            

            //先定义一个编辑的工作空间,然后把转化为数据集,最后转化为编辑工作空间, 
            IWorkspaceEdit w = (pFeatureClass as IDataset).Workspace as IWorkspaceEdit;

            //开始事务操作
            w.StartEditing(false);

            //开始编辑 
            w.StartEditOperation();            

            pPolygon = pPointColl as IPolygon;

            //封闭面对象
            pPolygon.Close();

            pPolygon.SpatialReference = spatialReference;
            pFeature.Shape = pPolygon;

            pFeatureCursor.InsertFeature(pFeatureBuffer);

            //Flush the feature cursor to the database
            pFeatureCursor.Flush();

            //结束编辑 
            w.StopEditOperation();

            //结束事务操作 
            w.StopEditing(true);
        }

        public IFeatureClass CreateFeatureClassWithFields(String featureClassName,
                                                    IFeatureWorkspace featureWorkspace)
        {
            // Instantiate a feature class description to get the required fields.
            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;
            IFields fields = ocDescription.RequiredFields;
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

            // Add a Name text field to the required fields.
            IField field = new FieldClass();
            IFieldEdit fieldEdit = (IFieldEdit)field;
            fieldEdit.Name_2 = "Name";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            fieldsEdit.AddField(field);

            // Use IFieldChecker to create a validated fields collection.
            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError = null;
            IFields validatedFields = null;
            fieldChecker.ValidateWorkspace = (IWorkspace)featureWorkspace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            // The enumFieldError enumerator can be inspected at this point to determine 
            // which fields were modified during validation.

            // Create the feature class.
            IFeatureClass featureClass = featureWorkspace.CreateFeatureClass
                (featureClassName, validatedFields, ocDescription.InstanceCLSID,
                ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple,
                fcDescription.ShapeFieldName, "");
            return featureClass;
        }


        private void cmenuZoomin_Click(object sender, EventArgs e)
        {
            //实现地图放大功能
            //Create a command instance.
            ICommand command = new ESRI.ArcGIS.Controls.ControlsMapZoomInToolClass();

            //Pass the MapControl to the OnCreate method.
            command.OnCreate(axMapControlMain.Object);

            //Set the MapControl's current tool.
            axMapControlMain.CurrentTool = command as ITool;

            //Call OnClick.
            command.OnClick();

        }

        private void cmenuZoomout_Click(object sender, EventArgs e)
        {
            //实现地图放大功能
            //Create a command instance.
            ICommand command = new ESRI.ArcGIS.Controls.ControlsMapZoomOutToolClass();

            //Pass the MapControl to the OnCreate method.
            command.OnCreate(axMapControlMain.Object);

            //Set the MapControl's current tool.
            axMapControlMain.CurrentTool = command as ITool;

            //Call OnClick.
            command.OnClick();
        }

        private void cmenuSelect_Click(object sender, EventArgs e)
        {
            //选择模式
            //Create a command instance.
            ICommand command = new ESRI.ArcGIS.Controls.ControlsSelectFeaturesToolClass();

            //Pass the MapControl to the OnCreate method.
            command.OnCreate(axMapControlMain.Object);

            //Set the MapControl's current tool.
            axMapControlMain.CurrentTool = command as ITool;

            //Call OnClick.
            command.OnClick();
        }

        private void addSdeDataset_Click(object sender, EventArgs e)
        {
            ISpatialReference pSpRef2;
            //pSpRef2 = this.createSpatialReferenceBeijing1954GK_20();
            pSpRef2 = this.createSpatialReference_Xian1980_3_Degree_GK_CM_111E();

            pSdeWorkspace.CreateFeatureDataset("elec", pSpRef2);

        }

        public ISpatialReference createSpatialReference_Xian1980_3_Degree_GK_CM_111E()
        {
            SpatialReferenceEnvironment pSpRFc;
            pSpRFc = new ESRI.ArcGIS.Geometry.SpatialReferenceEnvironment();            

            IProjectedCoordinateSystem pPCS;
           
            pPCS = pSpRFc.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_Beijing1954GK_20);
            pPCS = pSpRFc.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Xian1980_3_Degree_GK_CM_111E);

            //set the xy domain extent for the dataset 
            //SetDomain (XMin, XMax, YMin, YMax )
            //pPCS.SetDomain(427910.15, 804133.415, 3824803.83, 4523288.588);
            pPCS.SetDomain(-5123200, 900714802274.099, -10002100, 900709923374.099);

            //设置了Domain可以不设这个方法
            //pPCS.SetFalseOriginAndUnits(0, 0, 1000);

            ISpatialReference pSpRef2;
            pSpRef2 = pPCS;

            return pSpRef2;
        }


        public ISpatialReference createSpatialReferenceBeijing1954GK_20()
        {
            SpatialReferenceEnvironment pSpRFc;
            pSpRFc = new ESRI.ArcGIS.Geometry.SpatialReferenceEnvironment();

            IGeographicCoordinateSystem pGCS;
            pGCS = pSpRFc.CreateGeographicCoordinateSystem((int)esriSRGeoCS2Type.esriSRGeoCS_MajorAuxSphere_WGS1984);

            ISpatialReference pSpRef1;
            pSpRef1 = pGCS;
            pSpRef1.SetFalseOriginAndUnits(0, 0, 100);

            IProjectedCoordinateSystem pPCS;
            //pPCS = pSpRFc.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_Beijing1954GK_21);
            pPCS = pSpRFc.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_Beijing1954GK_20);

            //set the xy domain extent for the dataset 
            pPCS.SetDomain(20303481, 2851119422983.94, 3900994, 2851103020496.94);

            //设置了Domain可以不设这个方法
            //pPCS.SetFalseOriginAndUnits(0, 0, 1000);

            ISpatialReference pSpRef2;
            pSpRef2 = pPCS;

            return pSpRef2;

        }
        /// <summary>
        /// 增加Element
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addElement_Click(object sender, EventArgs e)
        {
            //增加线Element
            /*
            IGraphicsContainer m_pGraphicsContrainer;

            //IElement pElement;
            ILineElement pLineElement;
            pLineElement = new LineElementClass();

            IEnvelope pEnv;
            pEnv = axMapControl1.Extent;
            pEnv.Expand(0.5, 0.5, true);

            IPointCollection pLine;
            pLine = new PolylineClass();

            IPoint pPt1, pPt2, pPt3, pPt4;
            pPt1 = new PointClass();
            pPt2 = new PointClass();
            pPt3 = new PointClass();
            pPt4 = new PointClass();

            pPt1.PutCoords(pEnv.XMin, pEnv.YMin);
            pPt2.PutCoords(pEnv.XMin, pEnv.YMax);
            pPt3.PutCoords(pEnv.XMax, pEnv.YMax);
            pPt4.PutCoords(pEnv.XMax, pEnv.YMin);

            object missing = Type.Missing;

            pLine.AddPoint(pPt1, ref  missing, ref missing);
            pLine.AddPoint(pPt2, ref  missing, ref missing);
            pLine.AddPoint(pPt3, ref  missing, ref missing);
            pLine.AddPoint(pPt4, ref  missing, ref missing);
            pLine.AddPoint(pPt1, ref  missing, ref missing);


            pElement = pLineElement as IElement;
            pElement.Geometry = pLine as IGeometry;

            ILineSymbol pSymb;
            pSymb = new SimpleLineSymbolClass();
            IRgbColor pRGBColor = new RgbColorClass();

            pRGBColor.Red = 255;
            pRGBColor.Blue = 0;
            pRGBColor.Green = 0;

            pSymb.Color = pRGBColor;
            pSymb.Width = 2;

            pLineElement.Symbol = pSymb;
            m_pGraphicsContrainer = axMapControl1.Map as IGraphicsContainer;
            m_pGraphicsContrainer.AddElement(pElement, 0);

            this.axMapControlMain.Refresh();
            */

            //增加点的Element
            IElement pElement;

            IPoint pPoint;
            pPoint = new PointClass();
            pPoint.PutCoords(20625320 + 2000, 4158622 + 2000);
            

            IMarkerElement pMarkerElem;
            pMarkerElem = new MarkerElementClass();

            pElement = pMarkerElem as IElement;
            pElement.Geometry = pPoint as IGeometry;

            ESRI.ArcGIS.Display.ISimpleMarkerSymbol pMarkerSym;
            pMarkerSym = new ESRI.ArcGIS.Display.SimpleMarkerSymbolClass();

            pMarkerSym.Style = ESRI.ArcGIS.Display.esriSimpleMarkerStyle.esriSMSCircle;
            //pMarkerSym.Size = 100;

            IRgbColor pColor;
            pColor = new RgbColor();

            pColor.Red = 255;
            pColor.Blue = 0;
            pColor.Green = 0;

            pMarkerSym.Color = pColor;
            pMarkerElem.Symbol = pMarkerSym;

            IGraphicsContainer pGraphicsContrainer;
            pGraphicsContrainer = this.axMapControlMain.Map as IGraphicsContainer;
            pGraphicsContrainer.AddElement(pElement, 0);

            this.axMapControlMain.Refresh();

        }

        /// <summary>
        /// 增加点Element
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public void addPointElement(double x, double y)
        {
            IElement pElement;

            IPoint pPoint;
            pPoint = new PointClass();
            //pPoint.PutCoords(20625320 + 2000, 4158622 + 2000);
            pPoint.X = x;
            pPoint.Y = y;
            
            IMarkerElement pMarkerElem;
            pMarkerElem = new MarkerElementClass();

            pElement = pMarkerElem as IElement;
            pElement.Geometry = pPoint as IGeometry;

            ESRI.ArcGIS.Display.ISimpleMarkerSymbol pMarkerSym;
            pMarkerSym = new ESRI.ArcGIS.Display.SimpleMarkerSymbolClass();

            pMarkerSym.Style = ESRI.ArcGIS.Display.esriSimpleMarkerStyle.esriSMSCircle;
            //pMarkerSym.Size = 100;

            IRgbColor pColor;
            pColor = new RgbColor();

            pColor.Red = 255;
            pColor.Blue = 0;
            pColor.Green = 0;

            pMarkerSym.Color = pColor;
            pMarkerElem.Symbol = pMarkerSym;

            IGraphicsContainer pGraphicsContrainer;
            pGraphicsContrainer = this.axMapControlMain.Map as IGraphicsContainer;
            pGraphicsContrainer.AddElement(pElement, 0);

            this.axMapControlMain.Refresh();
        }

        private void axMapControlMain_OnMouseUp(object sender, IMapControlEvents2_OnMouseUpEvent e)
        {
            //增加点element
            //addPointElement(e.mapX, e.mapY);

            //空间选择与查找
            //spatialSelected(e.mapX, e.mapY);

            

        }        

        /// <summary>
        /// 空间选择与查找
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        private void spatialSelected(double x, double y)
        {
            IFeatureSelection pFeatSel;

            ISelectionSet pSelSet;


            pFeatSel = axMapControlMain.get_Layer(0) as IFeatureSelection;
            pFeatSel.Clear();

            IPoint pPoint;
            pPoint = new PointClass();
            pPoint.X = x;
            pPoint.Y = y;

            ITopologicalOperator ptopo;
            ptopo = pPoint as ITopologicalOperator;
            ptopo.Buffer(1000);

            ISpatialFilter pSF;
            pSF = new SpatialFilterClass();

            pSF.Geometry = ptopo as IGeometry;
            pSF.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;                      

            pFeatSel.SelectFeatures(pSF, esriSelectionResultEnum.esriSelectionResultNew, false);
            pFeatSel.SelectionChanged();

            this.axMapControlMain.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null);

            pSelSet = pFeatSel.SelectionSet;
            //MessageBox.Show(pSelSet.Count.ToString());
        }

        /// <summary>
        /// 简单渲染
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleRender_Click(object sender, EventArgs e)
        {
            //点渲染
            /*
            IGeoFeatureLayer pGeoFeatureL;
            pGeoFeatureL =this.axMapControl1.Map.get_Layer(0) as IGeoFeatureLayer;

            ISimpleRenderer pSimpleRenderer = new SimpleRendererClass ();

            ISimpleMarkerSymbol pmarkersym = new SimpleMarkerSymbolClass ();
            pmarkersym.Style = ESRI.ArcGIS.Display.esriSimpleMarkerStyle.esriSMSCircle;
            IRgbColor pcolor =new  RgbColorClass();
            pcolor.Red = 255;
            pcolor.Green = 0;
            pcolor.Blue = 0;
            pmarkersym.Color = pcolor;            
            pmarkersym.Size = 100;
            pmarkersym.Style = esriSimpleMarkerStyle.esriSMSDiamond ;

            pSimpleRenderer.Symbol = (ISymbol) pmarkersym;

            pGeoFeatureL.Renderer =(IFeatureRenderer )  pSimpleRenderer;

            this.axMapControl1.Refresh();

            */

            //线渲染
            IFeatureLayer layer;
            layer = axMapControlMain.get_Layer(0) as IFeatureLayer;
            //MessageBox.Show(layer.Name);            

            IGeoFeatureLayer pGeoLayer;
            pGeoLayer = layer as IGeoFeatureLayer;

            ISimpleRenderer pSimRen;
            pSimRen = new SimpleRendererClass();

            ILineSymbol pSymb;
            pSymb = new SimpleLineSymbolClass();
            IRgbColor pRGBColor = new RgbColorClass();

            pRGBColor.Red = 255;
            pRGBColor.Blue = 0;
            pRGBColor.Green = 0;

            pSymb.Color = pRGBColor;
            pSymb.Width = 2;

            pSimRen.Symbol = pSymb as ISymbol;
            pGeoLayer.Renderer = pSimRen as IFeatureRenderer;

            this.axMapControlMain.Refresh();
        }

        
        /// <summary>
        /// 唯一值渲染
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uniqueValueRender_Click(object sender, EventArgs e)
        {
            /*
            IFeatureLayer layer;
            layer = axMapControlMain.get_Layer(0) as IFeatureLayer;
            //MessageBox.Show(layer.Name);            

            IGeoFeatureLayer pGeoLayer;
            pGeoLayer = layer as IGeoFeatureLayer;

            IUniqueValueRenderer pRender = new UniqueValueRendererClass();

            //1
            ISimpleFillSymbol symd=new SimpleFillSymbolClass();

            IRgbColor pRGBColor = new RgbColorClass();
            pRGBColor.Red = 237;
            pRGBColor.Blue = 234;
            pRGBColor.Green = 108;

            symd.Style = esriSimpleFillStyle.esriSFSSolid;
            symd.Outline.Width = 0.4;
            symd.Color = pRGBColor;            

            //2
            IRgbColor pRGBColor1 = new RgbColorClass();
            pRGBColor.Red = 207;
            pRGBColor.Blue = 103;
            pRGBColor.Green = 239;

            ISimpleFillSymbol symd1 = new SimpleFillSymbolClass();
            symd1.Style = esriSimpleFillStyle.esriSFSSolid;
            symd1.Outline.Width = 0.4;
            symd1.Color = pRGBColor1;            

            //3
            IRgbColor pRGBColor2 = new RgbColorClass();
            pRGBColor.Red = 158;
            pRGBColor.Blue = 126;
            pRGBColor.Green = 216;

            ISimpleFillSymbol symd2 = new SimpleFillSymbolClass();
            symd2.Style = esriSimpleFillStyle.esriSFSSolid;
            symd2.Outline.Width = 0.4;
            symd2.Color = pRGBColor2;                       

            //4
            IRgbColor pRGBColor3 = new RgbColorClass();
            pRGBColor.Red = 222;
            pRGBColor.Blue = 120;
            pRGBColor.Green = 159;

            ISimpleFillSymbol symd3 = new SimpleFillSymbolClass();
            symd3.Style = esriSimpleFillStyle.esriSFSSolid;
            symd3.Outline.Width = 0.4;
            symd3.Color = pRGBColor3;

            pRender.FieldCount = 1;            

            pRender.set_Field(0, "VNAME");
            pRender.DefaultSymbol = symd as ISymbol;
            pRender.UseDefaultSymbol = true;

            pRender.AddValue("202", "VNAME", symd as ISymbol);
            pRender.set_Label("202", "202");
            pRender.set_Symbol("202", symd as ISymbol);

            pRender.AddValue("203", "VNAME", symd1 as ISymbol);
            pRender.set_Label("203", "203");
            pRender.set_Symbol("203", symd1 as ISymbol);

            pRender.AddValue("204", "VNAME", symd2 as ISymbol);
            pRender.set_Label("204", "204");
            pRender.set_Symbol("204", symd2 as ISymbol);

            pRender.AddValue("205", "VNAME", symd3 as ISymbol);
            pRender.set_Label("205", "205");
            pRender.set_Symbol("205", symd3 as ISymbol);

            pGeoLayer.Renderer = pRender as IFeatureRenderer;
            
            this.axTOCControl1.Update();

            this.axMapControlMain.Refresh();
            */

            //Layer must have "VNAME" field
            ILayer pLayer;
            pLayer = this.axMapControlMain.get_Layer(0);
            IFeatureLayer pFLayer;
            pFLayer = pLayer as IFeatureLayer;
            IGeoFeatureLayer pGFLayer;
            pGFLayer = pFLayer as IGeoFeatureLayer;

            IFeatureClass pFeatCls;
            pFeatCls = pFLayer.FeatureClass;
            IQueryFilter pQueryFilter;
            pQueryFilter = new QueryFilterClass();  //empty supports: SELECT *
            IFeatureCursor pFeatCursor;
            pFeatCursor=pFeatCls.Search(pQueryFilter,false);
            
            //** Make the color ramp we will use for the symbols in the renderer
            IRandomColorRamp rx;
            rx=new RandomColorRampClass();
            rx.MinSaturation=20;
            rx.MaxSaturation=40;
            rx.MinValue=85;
            rx.MaxValue=100;
            rx.StartHue=76;
            rx.EndHue=188;
            rx.UseSeed=true;
            rx.Seed=43;

            //** Make the renderer
            IUniqueValueRenderer pRender;
            pRender=new UniqueValueRendererClass();
            long n;
            ISimpleFillSymbol symd;
            symd=new SimpleFillSymbolClass();
            symd.Style=esriSimpleFillStyle.esriSFSSolid;
            symd.Outline.Width=0.4;

            //** These properties should be set prior to adding values
            pRender.FieldCount = 1;
            pRender.set_Field(0,"VNAME");
            pRender.DefaultSymbol=symd as ISymbol;
            pRender.UseDefaultSymbol=true;

            IFeature pFeat;
            n=pFeatCls.FeatureCount(pQueryFilter);

            //** Loop through the features
            
            bool ValFound;
            bool NoValFound;
            Int32 uh;
            IFields pFields;
            int iField;
            pFields = pFeatCursor.Fields;
            iField = pFields.FindField("VNAME");

            for(int i=0;i<n;i++)
            {
                ISimpleFillSymbol symx;
                symx = new SimpleFillSymbolClass();
                symx.Style=esriSimpleFillStyle.esriSFSSolid;
                symx.Outline.Width=0.4;
                pFeat = pFeatCursor.NextFeature();                
                String x;
                x = (string)pFeat.get_Value(iField); //*new Cory*
               
                //** Test to see if we've already added this value
                //** to the renderer, if not, then add it.
                ValFound = false;
                for(uh=0;uh<=pRender.ValueCount-1;uh++)
                {
                    if(pRender.get_Value(uh)==x)
                    {
                        NoValFound = true;
                        break;
                    }
                }

                if (!ValFound)
                {
                    pRender.AddValue(x,"VNAME",symx as ISymbol);
                    pRender.set_Label(x,x);
                    pRender.set_Symbol(x,symx as ISymbol);

                }
            }

            //** now that we know how many unique values there are
            //** we can size the color ramp and assign the colors.
            rx.Size =pRender.ValueCount;
            bool ok;
            ok = true;
            rx.CreateRamp(out ok);

            IEnumColors RColors;
            RColors = rx.Colors;
            RColors.Reset();

            Int32 ny;
            for (ny = 0; ny <= pRender.ValueCount - 1; ny++)
            {
                String xv;
                xv = pRender.get_Value(ny);            
                if (xv != "")
                {
                    ISimpleFillSymbol jsy;
                    jsy = new SimpleFillSymbolClass();
                    jsy.Color = RColors.Next();
                    pRender.set_Symbol(xv, jsy as ISymbol);
                }
            }

           //** If you didn't use a color ramp that was predefined
           //** in a style, you need to use "Custom" here, otherwise
           //** use the name of the color ramp you chose.
           pRender.ColorScheme = "Custom";
           pGFLayer.Renderer = pRender as IFeatureRenderer;
           pGFLayer.DisplayField = "VNAME";

           this.axTOCControl1.Update();

           this.axMapControlMain.Refresh();        
                
        }

        /// <summary>
        /// 建立要素类
        /// 分别是点线面要素类
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void createFeatureClass_Click(object sender, EventArgs e)
        {
            //open Featuredataset
            IFeatureDataset pFeatureDataset;
            pFeatureDataset = pSdeWorkspace.OpenFeatureDataset("elec");

            createTowerFeatureClass();
            createPointFeatureClass(pFeatureDataset);
            createLineFeatureClass(pFeatureDataset);
            createAreaFeatureClass(pFeatureDataset);
        }

        

        /// <summary>
        /// 建立点要素类
        /// </summary>
        /// <param name="pFeatureDataset"></param>        
        public void createPointFeatureClass(IFeatureDataset pFeatureDataset)
        {
            createSubstationFeatureClass(pFeatureDataset, "500kV");
            createSubstationFeatureClass(pFeatureDataset, "220kV");
            createSubstationFeatureClass(pFeatureDataset, "110kV");

        }

        /// <summary>
        /// 建立变电站要素类
        /// </summary>
        /// <param name="pFeatureDataset"></param>
        /// <param name="fcName"></param>
        /// <param name="fcAliasName"></param>
        /// <param name="voltage"></param>
        public void createSubstationFeatureClass(IFeatureDataset pFeatureDataset, string sVoltage)
        {
            IGeoDataset geoDataset = pFeatureDataset as IGeoDataset;
            ISpatialReference spatialReference = geoDataset.SpatialReference;

            IFields pFields = new FieldsClass();           
            IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;

            IField objectId;
            objectId = CreateObjectIdField();
            pFieldsEdit.AddField(objectId);

            IField shapeField;
            shapeField = CreateShapeField(spatialReference, esriGeometryType.esriGeometryPoint);
            pFieldsEdit.AddField(shapeField);

            //add field name
            IField known_as;
            known_as = CreatePropertyField("known_as", "变电站名称", esriFieldType.esriFieldTypeString, true, 50);
            pFieldsEdit.AddField(known_as);

            //add field substation_id_mis
            IField substation_id_mis;
            substation_id_mis = CreatePropertyField("substation_id_mis", "mis中变电站ID", esriFieldType.esriFieldTypeSingle, true, 50);
            pFieldsEdit.AddField(substation_id_mis);

            //add field Voltage
            IField Voltage;
            Voltage = CreatePropertyField("Voltage", "电压等级", esriFieldType.esriFieldTypeString, true, 50);
            pFieldsEdit.AddField(Voltage);

            string FeatureClassName;
            FeatureClassName = "substation";

            if (sVoltage == "500kV")
            {
                FeatureClassName = FeatureClassName + "_" + sVoltage;
            }
            else if (sVoltage == "220kV")
            {
                FeatureClassName = FeatureClassName + "_" + sVoltage;
            }
            else if (sVoltage == "110kV")
            {
                FeatureClassName = FeatureClassName + "_" + sVoltage;
            }
            else
            {
            }
            IFeatureClass substation;
            substation = pFeatureDataset.CreateFeatureClass(FeatureClassName, pFieldsEdit, null, null, esriFeatureType.esriFTSimple, "Shape", null);
        }

        /// <summary>
        /// 建立塔要素类
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void createTowerFeatureClass()
        {    
            //open Featuredataset
            IFeatureDataset pFeatureDataset;
            pFeatureDataset = pSdeWorkspace.OpenFeatureDataset("elec");

            IGeoDataset geoDataset = pFeatureDataset as IGeoDataset;
            ISpatialReference spatialReference = geoDataset.SpatialReference;

            IFields pFields = new FieldsClass();
            //IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;
            IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;

            IField objectId;
            objectId = CreateObjectIdField();
            pFieldsEdit.AddField(objectId);

            IField shapeField;
            shapeField = CreateShapeField(spatialReference, esriGeometryType.esriGeometryPoint);
            pFieldsEdit.AddField(shapeField);            

            //add field name
            IField known_as;
            known_as = CreatePropertyField("known_as", "杆号", esriFieldType.esriFieldTypeString, true, 50);
            pFieldsEdit.AddField(known_as);

            //add field wire_name
            IField wire_name;
            wire_name = CreatePropertyField("wire_name", "所属线路名称", esriFieldType.esriFieldTypeString, true, 50);
            pFieldsEdit.AddField(wire_name);

            //add field Voltage
            IField Voltage;
            Voltage = CreatePropertyField("Voltage", "电压等级", esriFieldType.esriFieldTypeString, true, 50);
            pFieldsEdit.AddField(Voltage);

            //add field tower_id_mis
            IField tower_id_mis;
            tower_id_mis = CreatePropertyField("tower_id_mis", "mis中塔ID", esriFieldType.esriFieldTypeSingle, true, 50);
            pFieldsEdit.AddField(tower_id_mis);
            
            IUID pUid = new UIDClass();
            pUid.Value = "esriGeoDatabase.Feature";

            IFeatureClass tower;
            tower = pFeatureDataset.CreateFeatureClass("tower", pFieldsEdit, null, null, esriFeatureType.esriFTSimple, "Shape", null);
            
        }

        /// <summary>
        /// 建立线要素类
        /// </summary>
        /// <param name="pFeatureDataset"></param>
        public void createLineFeatureClass(IFeatureDataset pFeatureDataset)
        {
            createWireFeatureClass(pFeatureDataset, "500kV");
            createWireFeatureClass(pFeatureDataset, "220kV");
            createWireFeatureClass(pFeatureDataset, "110kV");
            createWireFeatureClass(pFeatureDataset, "35kV");
        }

        /// <summary>
        /// 建立输电线路要素类
        /// </summary>
        /// <param name="pFeatureDataset"></param>
        /// <param name="sVoltage"></param>
        public void createWireFeatureClass(IFeatureDataset pFeatureDataset, string sVoltage)
        {
            IGeoDataset geoDataset = pFeatureDataset as IGeoDataset;
            ISpatialReference spatialReference = geoDataset.SpatialReference;

            IFields pFields = new FieldsClass();
            IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;

            IField objectId;
            objectId = CreateObjectIdField();
            pFieldsEdit.AddField(objectId);

            IField shapeField;
            shapeField = CreateShapeField(spatialReference, esriGeometryType.esriGeometryPolyline);
            pFieldsEdit.AddField(shapeField);

            //add field name
            IField known_as;
            known_as = CreatePropertyField("known_as", "线路名称", esriFieldType.esriFieldTypeString, true, 50);
            pFieldsEdit.AddField(known_as);

            //add field substation_id_mis
            IField wire_id_mis;
            wire_id_mis = CreatePropertyField("wire_id_mis", "mis中线路ID", esriFieldType.esriFieldTypeSingle, true, 50);
            pFieldsEdit.AddField(wire_id_mis);

            //add field Voltage
            IField Voltage;
            Voltage = CreatePropertyField("Voltage", "电压等级", esriFieldType.esriFieldTypeString, true, 50);
            pFieldsEdit.AddField(Voltage);

            string FeatureClassName;
            FeatureClassName = "hv_trolly_wire";

            if (sVoltage == "500kV")
            {
                FeatureClassName = FeatureClassName + "_" + sVoltage;
            }
            else if (sVoltage == "220kV")
            {
                FeatureClassName = FeatureClassName + "_" + sVoltage;
            }
            else if (sVoltage == "110kV")
            {
                FeatureClassName = FeatureClassName + "_" + sVoltage;
            }
            else if (sVoltage == "35kV")
            {
                FeatureClassName = FeatureClassName + "_" + sVoltage;
            }
            else
            {
            }

            IFeatureClass hv_trolly_wire;
            hv_trolly_wire = pFeatureDataset.CreateFeatureClass(FeatureClassName, pFieldsEdit, null, null, esriFeatureType.esriFTSimple, "Shape", null);
        }

        /// <summary>
        /// 建立面要素类
        /// </summary>
        /// <param name="pFeatureDataset"></param>
        private void createAreaFeatureClass(IFeatureDataset pFeatureDataset)
        {
            createDirtinessArea(pFeatureDataset, "1");
            createDirtinessArea(pFeatureDataset, "2");
            createDirtinessArea(pFeatureDataset, "3");
            createDirtinessArea(pFeatureDataset, "4");
        }

        /// <summary>
        /// 建立污秽区要素类
        /// </summary>
        /// <param name="pFeatureDataset"></param>
        /// <param name="index"></param>
        private void createDirtinessArea(IFeatureDataset pFeatureDataset, string sGrade)
        {
            IGeoDataset geoDataset = pFeatureDataset as IGeoDataset;
            ISpatialReference spatialReference = geoDataset.SpatialReference;

            IFields pFields = new FieldsClass();
            IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;

            IField objectId;
            objectId = CreateObjectIdField();
            pFieldsEdit.AddField(objectId);

            IField shapeField;
            shapeField = CreateShapeField(spatialReference, esriGeometryType.esriGeometryPolygon);
            pFieldsEdit.AddField(shapeField);

            //add field name
            IField known_as;
            known_as = CreatePropertyField("known_as", "污秽区名称", esriFieldType.esriFieldTypeString, true, 50);
            pFieldsEdit.AddField(known_as);

            //add field DirtinessArea
            IField DirtinessArea_id_mis;
            DirtinessArea_id_mis = CreatePropertyField("DirtinessArea_id_mis", "mis中污秽区ID", esriFieldType.esriFieldTypeSingle, true, 50);
            pFieldsEdit.AddField(DirtinessArea_id_mis);

            //add field Voltage
            IField grade;
            grade = CreatePropertyField("grade", "污秽等级", esriFieldType.esriFieldTypeString, true, 50);
            pFieldsEdit.AddField(grade);

            string FeatureClassName;
            FeatureClassName = "DirtinessArea";

            if (sGrade == "1")
            {
                FeatureClassName = FeatureClassName + "_" + sGrade;
            }
            else if (sGrade == "2")
            {
                FeatureClassName = FeatureClassName + "_" + sGrade;
            }
            else if (sGrade == "3")
            {
                FeatureClassName = FeatureClassName + "_" + sGrade;
            }
            else if (sGrade == "4")
            {
                FeatureClassName = FeatureClassName + "_" + sGrade;
            }
            else
            {
            }

            IFeatureClass DirtinessArea;
            DirtinessArea = pFeatureDataset.CreateFeatureClass(FeatureClassName, pFieldsEdit, null, null, esriFeatureType.esriFTSimple, "Shape", null);
        }

        /// <summary>
        /// 建立objectid字段
        /// </summary>
        /// <returns></returns>
        public IField CreateObjectIdField()
        {            
            //Create Object ID Field
            IField pField = new FieldClass();
            IFieldEdit pFieldEdit = (IFieldEdit)pField;

            pFieldEdit.Name_2 = "OBJECTID";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;            
            pFieldEdit.AliasName_2 = "几何对象ID";
            return pField;
        }

        /// <summary>
        /// 建立shape字段
        /// </summary>
        /// <param name="spatialReference"></param>
        /// <param name="GeomType"></param>
        /// <returns></returns>
        public IField CreateShapeField(ESRI.ArcGIS.Geometry.ISpatialReference spatialReference, esriGeometryType GeomType)
        {           
            // Note that if the spatial reference is not passed in
            //the resulting feature class will either have an unknown spatial 
            //reference or it will be inherited from a feature dataset.

            Int32 numPoints = 1;

            //create a new Geometry Definition
            IGeometryDef geometryDef = new GeometryDefClass();
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;

            switch (GeomType)
            {
                case esriGeometryType.esriGeometryPoint:
                    numPoints = 1;
                    break;
                case esriGeometryType.esriGeometryPolyline:
                    numPoints = 2;
                    break;
                case esriGeometryType.esriGeometryPolygon:
                    numPoints = 4;
                    break;
                default:
                    numPoints = 5;
                    break;
            }

            geometryDefEdit.AvgNumPoints_2 = numPoints;
            //geometryDefEdit.GeometryType_2 = ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline;
            geometryDefEdit.GeometryType_2 = GeomType;

            //hardcode grid levels if you know what will work best in your case.        
            /*geometryDefEdit.GridCount_2 = 2;        
             * //grid index is zero based        
             * geometryDefEdit.set_GridSize(0, 200);        
             * geometryDefEdit.set_GridSize(1, 500);
             */        
            //otherwise allow ArcGIS to set valid grid values based on the features added.  
            //We will set the first grid size to zero and allow ArcGIS to determine a valid gridsize.
            geometryDefEdit.GridCount_2 = 1;        
            geometryDefEdit.set_GridSize(0, 0);        
            geometryDefEdit.HasM_2 = false;
            geometryDefEdit.HasZ_2 = false;        
                                               
            if (spatialReference != null)
            {
                geometryDefEdit.SpatialReference_2 = spatialReference;
            }

            //create Shape Field
            IField field = new FieldClass();
            //cast for IFieldEdit
            IFieldEdit fieldEdit = (IFieldEdit)field;
            //IFieldEdit::GeometryDef
            fieldEdit.Name_2 = "SHAPE";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            fieldEdit.AliasName_2 = "几何位置";
            fieldEdit.IsNullable_2 = true;
            fieldEdit.Editable_2 = true;
            fieldEdit.GeometryDef_2 = geometryDef;
            return field;
        }

        /// <summary>
        /// 建立属性字段
        /// </summary>
        /// <param name="fieldname"></param>
        /// <param name="aliasname"></param>
        /// <param name="filedtype"></param>
        /// <param name="allownull"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public IField CreatePropertyField(string fieldname,string aliasname,esriFieldType filedtype, Boolean allownull, Int32 length )
        {
            //create Field
            IField field = new FieldClass();
            //cast for IFieldEdit
            IFieldEdit fieldEdit = (IFieldEdit)field;

            switch (filedtype)
            {
                case esriFieldType.esriFieldTypeSmallInteger:
                    fieldEdit.Name_2 = fieldname;
                    fieldEdit.Type_2 = filedtype;
                    fieldEdit.AliasName_2 = aliasname;
                    fieldEdit.IsNullable_2 = allownull;
                    break;
                case esriFieldType.esriFieldTypeInteger:
                    fieldEdit.Name_2 = fieldname;
                    fieldEdit.Type_2 = filedtype;
                    fieldEdit.AliasName_2 = aliasname;
                    fieldEdit.IsNullable_2 = allownull;
                    break;
                case esriFieldType.esriFieldTypeSingle:
                    fieldEdit.Name_2 = fieldname;
                    fieldEdit.Type_2 = filedtype;
                    fieldEdit.AliasName_2 = aliasname;
                    fieldEdit.IsNullable_2 = allownull;
                    break;
                case esriFieldType.esriFieldTypeDouble:
                    fieldEdit.Name_2 = fieldname;
                    fieldEdit.Type_2 = filedtype;
                    fieldEdit.AliasName_2 = aliasname;
                    fieldEdit.IsNullable_2 = allownull;
                    break;
                case esriFieldType.esriFieldTypeString:
                    fieldEdit.Name_2 = fieldname;
                    fieldEdit.Type_2 = filedtype;
                    fieldEdit.AliasName_2 = aliasname;
                    fieldEdit.IsNullable_2 = allownull;
                    fieldEdit.Length_2 = length;
                    break;
                case esriFieldType.esriFieldTypeDate:
                    fieldEdit.Name_2 = fieldname;
                    fieldEdit.Type_2 = filedtype;
                    fieldEdit.AliasName_2 = aliasname;
                    fieldEdit.IsNullable_2 = allownull;
                    break;
                default:
                    break;
            }

            return field;
        }

        private void menuTowerEdit_Click(object sender, EventArgs e)
        {
            //开始用鼠标交互录入杆塔
            //设置录入状态,1为编辑状态
            GlobalVariableDefined.pMouseOperateState = (int)enumMouseOperateState.editing;
            GlobalVariableDefined.CurrentEditLayer="SDE.Tower";


            
        }

        private void menuWireEdit500KV_Click(object sender, EventArgs e)
        {
            //开始用鼠标交互录入线路
            //设置录入状态,1为编辑状态
            GlobalVariableDefined.pMouseOperateState = (int)enumMouseOperateState.editing;
            GlobalVariableDefined.CurrentEditLayer = "SDE.Hv_trolly_wire_500kV";

            //初始化全局变量pPointColl
            IPolyline pPolyline = new PolylineClass();
            pPointColl = pPolyline as IPointCollection;

        }

        private void menuDirtinessArea1_Click(object sender, EventArgs e)
        {
            //开始用鼠标交互录入污秽区
            //设置录入状态,1为编辑状态
            GlobalVariableDefined.pMouseOperateState = (int)enumMouseOperateState.editing;
            GlobalVariableDefined.CurrentEditLayer = "SDE.DirtinessArea_1";

            //初始化全局变量pPointColl
            IPolygon pPolylgon = new PolygonClass();
            pPointColl = pPolylgon as IPointCollection;

        }

        private void deleteDataset_Click(object sender, EventArgs e)
        {

            IDataset pDataset;
            IFeatureDataset pFeatureDataset;
            pFeatureDataset = pSdeWorkspace.OpenFeatureDataset("elec");
            pDataset = pFeatureDataset as IDataset;
            pDataset.Delete();

        }

        private void reLoadLayer_Click(object sender, EventArgs e)
        {
            //连接SDE数据库
            pSdeWorkspace = UserDatabaseOperation.openSDEWorkspace("zymobile", "esri_sde", "port:5151", "sde", "sde", "", "sde.DEFAULT");
            //加载图层
            AddSdeLayer();
        }

        private void menuWireEdit_Click(object sender, EventArgs e)
        {

        }

           

        
       
    }
}